package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"strconv"
	"strings"
)

// config struct
type config struct {
	Root string
	Port string
}

var conf config

func init() {
	conf_file, err := os.Open("./z.conf")
	defer conf_file.Close()
	if err != nil {
		panic(err)
	}
	fileInfo, err := conf_file.Stat()
	if err != nil {
		panic("config file not found \n")
	}
	fileSize := fileInfo.Size()
	conf_buf := make([]byte, fileSize)
	if _, err := conf_file.Read(conf_buf); err != nil {
		panic(err)
	}
	dec := json.NewDecoder(strings.NewReader(string(conf_buf)))
	if errs := dec.Decode(&conf); errs != nil {
		panic(errs)
	}
}

func main() {
	worker_num := 0
	c := make(chan string)
	code := make(chan int)
	index := func(w http.ResponseWriter, req *http.Request) {
		worker_num++
		go worker(c, code, req, worker_num)
		w.WriteHeader(<-code)
		io.WriteString(w, <-c)
	}
	http.HandleFunc("/", index)
	http.ListenAndServe(conf.Port, nil)
}

func worker(c chan string, code chan int, req *http.Request, num int) {
	if req.RequestURI != "/stat" {
		var req_path string = ""
		if req.RequestURI == "/" {
			req_path = conf.Root + "/index.html"
		} else {
			req_path = conf.Root + req.RequestURI
		}
		file, err := os.Open(req_path)
		defer file.Close()
		if err != nil {
			code <- 404
			c <- "Not Found"
			return
		}
		fileInfo, err := file.Stat()
		if err != nil {
			panic(err)
		}
		fileSzie := fileInfo.Size()
		data := make([]byte, fileSzie)
		if _, err := file.Read(data); err != nil {
			panic(err)
		}
		code <- 200
		c <- string(data)
	} else {
		code <- 200
		c <- "worker : " + strconv.Itoa(num) + " : hello, this is ok"
	}
	fmt.Println(req.Method, req.URL)
	fmt.Println(req.RemoteAddr)
}
